import os

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
import sys

from ClientUi.controls.CustomList import CustomList, CustomListItemType
from ClientUi.deviceManager.camera_params_setting import camera_params_setting
from ClientUi.deviceManager.deviceManagerBaseDlg import deviceManagerBaseDlg
from ClientUi.deviceManager.search_camera import search_camera_wnd
from get_config import config, config_save
from ClientUi.deviceManager.dev_config import max_camera_num, global_camera_type, global_config_key_camera_type

class cameraSettingDlg(deviceManagerBaseDlg):
    def __init__(self):
        super().__init__()
        self.setWindowIcon(QIcon(f'{self._clientUiPath}\\images\\icon.ico'))  # 设置窗口图标
        self.setWindowTitle('相机管理')
        cameraList = self._getDevList()
        # 表格中控件绑定事件
        if cameraList is not None:
            cameraList.connectComboBox(1, self.__changeCameraType)
            cameraList.connectButton(2, self.__clickSearchDev)
            cameraList.connectLineEdit(3, self.__changeCameraIp)
            cameraList.connectLineEdit(4, self.__changeCameraName)
            cameraList.connectButton(5, self.__clickSetDev)
            cameraList.connectButton(6, self.__clickClearInfo)

    def _onInitTopWidget(self):
        self._createTopWidget('相机数量：', max_camera_num, config.get('cameranum', 1))

    def _onInitDevListHeader(self, devList: CustomList):
        devList.SetColumnTitleAndTypes((('序号', CustomListItemType.LABEL),
                                        ('选择品牌', CustomListItemType.COMBOBOX),
                                        ('搜索', CustomListItemType.BUTTON),
                                        ('IP', CustomListItemType.EDIT),
                                        ('备注名称', CustomListItemType.EDIT),
                                        ('配置', CustomListItemType.BUTTON),
                                        ('清除', CustomListItemType.BUTTON)))
        devList.SetEditMaxLen(3, 15)
        devList.SetEditMaxLen(4, 10)

    def _onInitDevListRows(self, rowCount: int, devList: CustomList):
        devList.setRowCount(rowCount)
        for i in range(rowCount):
            devList.setRow(i, (f'{i + 1}', (global_camera_type, config.get(f'camera{i + 1}_type', '')), '搜索',
                               config.get(f'camera{i + 1}_devinfo', ''), config.get(f'camera{i + 1}_name', ''), '设置',
                                         {'icon': f'{self._clientUiPath}\\images\\reset.png'}))

        return 0
    
    def _onSave(self):
        for camtype in global_config_key_camera_type:
            config[camtype] = 0
        config['cameranum'] = self._getCurrentDevNum()
        for i in range(config['cameranum']):
            result = self.__getRowInfo(i)
            print(result)
            config[f"camera{i + 1}_type"] = index = result[1]
            config[f"camera{i + 1}_devinfo"] = result[3]
            config[f"camera{i + 1}_name"] = result[4]
            # 之前算法设置界面，只要勾选了某个相机，就将某个相机对应的config进行设置为非0
            config[global_config_key_camera_type[index]] = 1
        # for camtype in global_config_key_camera_type:
            # print(f'config[{camtype}]: {config[camtype]}')
        config_save()
        self.accept()

    def __getRowInfo(self, rowIndex: int):
        return self._getDevList().getRow(rowIndex)

    def __clickSearchDev(self, row: int, column: int):
        print(f'__clickSearchDev: {row} {column}')
        wd = search_camera_wnd(row, 0)
        def onSearchedCamera(info):
            index = wd.camidx
            if len(info) > 0 and index >= 0:
                self._getDevList().setCell(index, 3, info[0])
        wd.selected_cam_signal.connect(onSearchedCamera)
        wd.exec_()

    def __clickSetDev(self, row: int, column: int):
        print(f'__clickSetDev: {row} {column}')
        wd = camera_params_setting(row)
        wd.exec_()

    def __clickClearInfo(self, row: int, column: int):
        print(f'__clickClearInfo: {row} {column}')
        self._getDevList().clearRow(row, [CustomListItemType.EDIT, CustomListItemType.COMBOBOX])

    def __changeCameraType(self, row: int, column: int, index: int):
        print(f'__changeCameraType: {row} {column}, {index}')

    def __changeCameraIp(self, row: int, column: int, ip: str):
        print(f'__changeCameraType: {row} {column}, {ip}')

    def __changeCameraName(self, row: int, column: int, name: str):
        print(f'__changeCameraType: {row} {column}, {name}')


def test_cameraSettingDlg():
    app = QApplication(sys.argv)
    current_path = os.path.abspath(__file__)
    path = os.path.dirname(current_path)
    path = os.path.dirname(path)
    #app.setStyleSheet(open(f'{path}/styleSheet.qss', encoding='utf-8').read())
    window = cameraSettingDlg()
    window.showNormal()
    sys.exit(app.exec_())
    return 0

if __name__ == '__main__':
    test_cameraSettingDlg()